package com.hyy.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyy.common.pojo.Result;
import com.hyy.common.utils.JWTUtils;
import com.hyy.gateway.properties.AuthWhiteName;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/*
* 用户认证的过滤器
* */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {


    @Autowired
    private ObjectMapper objectMapper;

//    //把这里白名单放到naocs配置中
//    private List<String> whiteNames=List.of("/user/login","/user/register");
    @Autowired
    private AuthWhiteName authWhiteName;

    //exchange可以拿到请求或者响应
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //配置白名单,如果请求Url在白名单，那么放行
        ServerHttpRequest request= exchange.getRequest();
        ServerHttpResponse response=exchange.getResponse();
        String path=request.getURI().getPath();
        if(math(path,authWhiteName.getUrl())){
            //放行
            return chain.filter(exchange);
        }

        String userToken=request.getHeaders().getFirst("user_token");
        log.info("header中获取token: {}",userToken);
        if(!StringUtils.hasLength(userToken)){
            //TODO  拦截
            return unauthorizedResponse(exchange,"令牌不能为空");
        }

        Claims claims= JWTUtils.parseJWT(userToken);
        if(claims==null){
            log.info("令牌验证失败");
            //TODO
            return unauthorizedResponse(exchange,"令牌过期或者不合法");
        }

        return chain.filter(exchange);
    }

    private boolean math(String path, List<String> url) {
        if(url==null||url.size()==0){
            return false;
        }
        if(url.contains(path)){return true;}
        return false;
    }

    @SneakyThrows//这个注解可以自动加一个try catch
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String  errMsg){
        log.error("用户认证失败，url={}",exchange.getRequest().getURI().toString());
        ServerHttpResponse response=exchange.getResponse();
        //响应设置成401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);

        //响应格式编程json
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        Result result=Result.fail(errMsg);

        //把Result对象封装成一个DdataBuffer对象
        DataBuffer dataBuffer=response.bufferFactory().wrap(objectMapper.writeValueAsBytes(result));
        return response.writeWith(Mono.just(dataBuffer));
    }


    @Override
    public int getOrder() {
        return -200;
    }
}
